package com.huaxin.hxcloud.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseSectionQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.Org;
import com.huaxin.common.Entity.StationDTO;
import com.huaxin.common.Entity.StationListDTO;
import com.huaxin.common.Entity.StationSection;
import com.huaxin.common.Global;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tts.Constant;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.utils.Util;
import com.huaxin.common.view.RoundLayout;
import com.huaxin.common.view.pulltorefresh.CustomHeaderLayout;
import com.huaxin.common.view.pulltorefresh.PullToRefreshBase;
import com.huaxin.common.view.pulltorefresh.extras.recyclerview.PullToRefreshRecyclerView;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.work.HxStationInfoActivity;
import com.huaxindata.im.main.manager.UserManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/9/21.
 * 工作 站点
 */
public class StationListActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener2 {


    @BindView(R.id.title)
    TextView                  mTitle;
    @BindView(R.id.ll_title)
    LinearLayout              llTitle;
    @BindView(R.id.map)
    ImageView                 map;
    @BindView(R.id.toolbar)
    Toolbar                   toolbar;
    @BindView(R.id.pull_view)
    PullToRefreshRecyclerView pullView;
    @BindView(R.id.tv_station_header)
    TextView                  tv_station_header;

    RecyclerView stationList;
    private ArrayList<StationSection> datas = new ArrayList<>();
    private StationListAdapter stationListAdapter;
    private boolean childState = false;
    private String  orgCode    = null;
    private String orgName;
    private Org    curOrg;

    private String mStationCode = null;
    private ArrayList<StationDTO> stationlists;
    private View                  emptyView;
    //station type 分类
    List<StationSection> companys = new ArrayList<>();
    List<StationSection> staions  = new ArrayList<>();

    @Override
    protected int getContentViewId() {
        return R.layout.activity_station_list;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    /**
     * 动态设置箭头颜色
     * @param drawableRes
     */
    private void setTitleEndImg(@DrawableRes int drawableRes) {
        Drawable drawable = getResources().getDrawable(drawableRes);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
        mTitle.setCompoundDrawables(null, null, drawable, null);//画在右边
    }

    @Override
    public void initView() {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        if (Constant.SPTOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
            //不可点击
            llTitle.setClickable(false);
            setTitleEndImg(R.drawable.icon_down);
        } else {
            llTitle.setClickable(true);
            setTitleEndImg(R.drawable.arow_down);
        }


        pullView.setHeaderLayout(new CustomHeaderLayout(this));
        pullView.setOnRefreshListener(this);
        stationList = pullView.getRefreshableView();
        stationList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        stationListAdapter = new StationListAdapter(R.layout.item_station, R.layout.header_station, datas);

        stationList.setAdapter(stationListAdapter);
        //空布局
        emptyView = LayoutInflater.from(this).inflate(R.layout.item_empty_nodata_center, (ViewGroup) stationList.getParent(), false);

        //item 点击事件
        stationListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                StationSection stationSection = datas.get(position);
                if (!stationSection.isHeader) {
                    StationDTO data = stationSection.t;
                    Intent intent = new Intent(StationListActivity.this, HxStationInfoActivity.class);
                    intent.putExtra(Constants.IK_STATION_CODE, data.getStationCode());
                    intent.putExtra(Constants.IK_STATION_TYPE, data.getType());
                    startActivity(intent);
                } else {
                    if (position == 0) {
                        datas.clear();
                        if (stationSection.isExpand) {
                            // stationSection.setExpand(false);
                            datas.add(new StationSection(true, staions.get(0).t.getOrgName(), false));
                            //datas.addAll(staions);
                            datas.add(new StationSection(true, "", false));
                            datas.addAll(companys);
                        } else {
                            // stationSection.setExpand(true);
                            datas.add(new StationSection(true, staions.get(0).t.getOrgName(), true));
                            datas.addAll(staions);
                            datas.add(new StationSection(true, "", false));
                            datas.addAll(companys);
                        }
                        stationListAdapter.setNewData(datas);
                    }
                }
            }
        });

        //            stationList.addOnScrollListener(new RecyclerView.OnScrollListener() {
        //                @Override
        //                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        //                    super.onScrollStateChanged(recyclerView, newState);
        //                    //newstate 当前滑动状态
        //                    Log.e("lwjing", "newstate " + newState);
        //
        //                    //判断是当前layoutManager是否为LinearLayoutManager
        //                    // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
        //                    LinearLayoutManager linearManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        //
        //                    //第一个可见isheader false  第一个和最后一个 type 2 显示
        //                    //                  true  最后一个 type 2 显示
        //                    int lastVisibleItemPosition = linearManager.findLastVisibleItemPosition();
        //                    //获取第一个可见view的位置
        //                    int firstVisibleItemPosition = linearManager.findFirstVisibleItemPosition();
        //                    Log.e("lwjing", "firstItemPosition " + firstVisibleItemPosition + " " + datas.get(firstVisibleItemPosition).isHeader);
        //
        //                    if (datas.get(firstVisibleItemPosition).t.getType() == 2 && datas.get(lastVisibleItemPosition).t.getType() == 2) {
        //                        //tv_station_header.setVisibility(View.VISIBLE);
        //
        //                        ObjectAnimator anim = ObjectAnimator.ofFloat(tv_station_header, "alpha", 0f, 0.1f,0.5f, 1f);
        //                        anim.setDuration(1000);
        //                        anim.start();
        //
        //                    } else {
        //                      //  tv_station_header.setVisibility(View.GONE);
        //                        ObjectAnimator anim = ObjectAnimator.ofFloat(tv_station_header, "alpha", 1f,0.5f,0.1f,0f);
        //                        anim.setDuration(1000);
        //                        anim.start();
        //                    }
        //
        //
        //                }
        //            });

    }

    @Override
    public void initData() {
        if (!Util.checkNull(Global.user)) {
            orgCode = Global.user.getOrgCode();
            orgName = Global.user.getOrgName();
            loadText(mTitle, orgName);
        }
    }

    @Override
    protected void requestData() {
        ApiRequestData(LOADING, null);
    }

    private void ApiRequestData(int status, final PullToRefreshBase refreshView) {
        if (refreshView == null) {
            updateLoadStatus(status);
        }
        Call<StationListDTO> call = HxTransmitRequestHelper.getRequestApi().getStationList(orgCode, mStationCode);
        autoClose(call);
        Log.d(TAG, "ApiRequestData: " + call.request().url());
        call.enqueue(new Callback<StationListDTO>() {
            @Override
            public void onResponse(Call<StationListDTO> call, Response<StationListDTO> response) {
                StationListDTO stationListDTO = response.body();
                if (response.isSuccessful() && stationListDTO != null) {
                    if (refreshView == null) {
                        updateLoadStatus(LOAD_SUCCESS);
                    } else {
                        refreshView.onRefreshComplete();
                    }
                    updateView(stationListDTO);

                } else {
                    if (refreshView == null) {
                        updateLoadStatus(LOAD_ERROR);
                    } else {
                        refreshView.onRefreshComplete();
                    }
                }
            }

            @Override
            public void onFailure(Call<StationListDTO> call, Throwable t) {
                Log.d(TAG, "onFailure: ---->" + t);
                //                updateLoadStatus(LOAD_FAILURE);
                if (refreshView == null) {
                    updateLoadStatus(LOAD_FAILURE);
                } else {
                    refreshView.onRefreshComplete();
                }
            }
        });

    }


    /**
     * stationlist 数据更新
     *
     * @param stationListDTO
     */
    private void updateView(StationListDTO stationListDTO) {
        stationlists = stationListDTO.getStationList();
        Org org = stationListDTO.getOrg();
        if (org != null) {
            curOrg = org;
        }
        //   Log.d("lwjing", "updateView: ---->" + curOrg.getOrgName());
        if (curOrg != null && curOrg.getOrgName() != null) {
            loadText(mTitle, curOrg.getOrgName());

        }
        datas.clear();
        if (stationlists == null || stationlists.isEmpty()) {
            //设置空布局
            stationListAdapter.setNewData(datas);
            stationListAdapter.setEmptyView(emptyView);
            return;
        }

        companys.clear();
        staions.clear();
        for (int i = 0; i < stationlists.size(); i++) {
            StationDTO stationDTO = stationlists.get(i);
            if (stationDTO.getType() == 1) {
                //厂
                companys.add(new StationSection(stationDTO));
            } else {
                //站点
                staions.add(new StationSection(stationDTO));
            }
        }

        if (companys.size() != 0 && staions.size() != 0) {
            if (staions.get(0).t.getOrgName() != null && !staions.get(0).t.getOrgName().contains("村镇站点")) {
                datas.add(new StationSection(true, staions.get(0).t.getOrgName() + "村镇站点", false));
            } else {
                datas.add(new StationSection(true, staions.get(0).t.getOrgName(), false));
            }
            //  datas.addAll(staions);
            datas.add(new StationSection(true, "", false));
            datas.addAll(companys);

        } else {
            datas.addAll(companys);
            datas.addAll(staions);
        }

        //设置数据
        stationListAdapter.setNewData(datas);
        //stationListAdapter.notifyDataSetChanged();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == Constants.RET_SELECT_ORG) {
            curOrg = data.getParcelableExtra(Constants.IK_ORG);
            Log.d(TAG, "onActivityResult: --1-->" + curOrg.getOrgCode());
            Log.d(TAG, "onActivityResult: --2-->" + curOrg.getOrgName());
            Log.d(TAG, "onActivityResult: --3-->" + curOrg.getStationCode());
            orgCode = curOrg.getOrgCode();
            mStationCode = curOrg.getStationCode();
            loadText(mTitle, curOrg.getOrgName());
            ApiRequestData(LOADING, null);
        }
    }

    @OnClick({R.id.ll_title, R.id.map})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.map:
                if (curOrg != null && !datas.isEmpty()) {
                    StationMapActivity.start(this, curOrg, stationlists);
                } else {
                    ToastUtil.showToast("该区域无站点！");
                }
                break;
            case R.id.ll_title:
                AreaSelectActivity.start(this, curOrg);
                break;
            default:
                break;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        ApiRequestData(LOADING, refreshView);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        refreshView.onRefreshComplete();
    }

    class StationListAdapter extends BaseSectionQuickAdapter<StationSection, BaseViewHolder> {

        public StationListAdapter(int layoutResId, int sectionHeadResId, List<StationSection> data) {
            super(layoutResId, sectionHeadResId, data);

        }

        @Override
        protected void convertHead(BaseViewHolder baseViewHolder, StationSection stationSection) {
            baseViewHolder.setText(R.id.header, stationSection.header);
            ImageView iv_station_icon = baseViewHolder.getView(R.id.iv_station_icon);
            ImageView iv_arrow = baseViewHolder.getView(R.id.iv_arrow);
            if ("".equals(stationSection.header)) {
                iv_station_icon.setVisibility(View.GONE);
                iv_arrow.setVisibility(View.GONE);
                baseViewHolder.itemView.setBackgroundColor(getResources().getColor(R.color.divider));
            } else {
                iv_station_icon.setVisibility(View.VISIBLE);
                iv_arrow.setVisibility(View.VISIBLE);
                baseViewHolder.itemView.setBackgroundColor(Color.WHITE);

                if (stationSection.isExpand) {
                    iv_arrow.setImageResource(R.drawable.icon_down);
                } else {
                    iv_arrow.setImageResource(R.drawable.ic_arrow_right);
                }
            }
        }

        @Override
        protected void convert(BaseViewHolder holder, StationSection stationSection) {
            //   dvTop.setVisibility(position == 0 ? View.VISIBLE : View.GONE);
            //  this.position = position;
            ImageView img = holder.getView(R.id.img);
            RoundLayout rlImg = holder.getView(R.id.rl_img);
            TextView stationName = holder.getView(R.id.stationName);
            TextView buildAddress = holder.getView(R.id.buildAddress);
            TextView ownerName = holder.getView(R.id.ownerName);
            TextView phone = holder.getView(R.id.phone);
            View dvTop = holder.getView(R.id.dv_top);
            TextView state = holder.getView(R.id.state);
            StationDTO data = stationSection.t;
            // StationDTO data = (StationDTO) datas.get(position);
            setStateText(state, data.getStationState());
            loadNetImg(img, data.getStationImg());
            loadText(stationName, data.getStationName());
            loadText("所属区域：", buildAddress, data.getAddress(), "暂无");
            loadText("负责人：", ownerName, data.getContactPerson(), "暂无");
            loadText(phone, data.getContactPhone());
        }

        private void setStateText(TextView textView, int state) {
            int static_normal = getResources().getColor(R.color.state_green);
            int static_bug = getResources().getColor(R.color.state_orange);
            int static_out = getResources().getColor(R.color.state_gray);
            //站点状态 0:正常，1：通讯超时，2、故障，3、待初始化
            textView.setVisibility(View.VISIBLE);
            switch (state) {
                case 0:
                    textView.setText("正常");
                    textView.setTextColor(static_normal);
                    textView.setBackgroundResource(R.drawable.bg_normal_green);
                    break;
                case 1:
                    textView.setText("超时");
                    textView.setTextColor(static_bug);
                    textView.setBackgroundResource(R.drawable.bg_bug);
                    break;
                case 2:
                    textView.setText("故障");
                    textView.setTextColor(static_bug);
                    textView.setBackgroundResource(R.drawable.bg_bug);
                    break;
                case 3:
                    textView.setText("待初始化");
                    textView.setTextColor(static_bug);
                    textView.setBackgroundResource(R.drawable.bg_bug);
                    break;
                default:
                    textView.setVisibility(View.GONE);
                    break;
            }
        }

    }
}
